package product;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.DecimalFormat;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableRowSorter;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;

public class Sale extends JInternalFrame {
	private JPanel panel;
	private JPanel panel_1;
	private JTextField code;
	private JLabel lblNewLabel;
	private JLabel label;
	private JTextField irum;
	private JLabel label_1;
	private JTextField pric;
	private JLabel label_2;
	private JTextField customer;
	private JLabel label_3;
	private JTextField EA;
	private JLabel label_4;
	private JTextField saleEa;
	private JPanel panel_2;
	private JPanel panel_3;
	private JTextField findStr;
	private JButton btnNewButton;
	private JScrollPane scrollPane;
	private JTable table;
	DefaultTableModel model;
	Connection con;
	DecimalFormat df = new DecimalFormat("###,###,###.##");
	Vector<String> col = new Vector<String>();
	int index;
	ProductMain5 m;
	private JButton btnNewButton_1;
	private JPanel panel_4;

	public Sale(Connection c,ProductMain5 main) {
		super("판매리스트", true, true, true, true);
		this.con = c;
		this.m = main;
		addInternalFrameListener(new InternalFrameAdapter() {
			@Override
			public void internalFrameClosed(InternalFrameEvent arg0) {
				m.saleInput = null;
			}
		});
		col.add("제품코드");
		col.add("제품명");
		col.add("판매가");
		col.add("거래처");
		col.add("재고");
		model = new DefaultTableModel(col, 0) {
			public boolean isCellEditable(int rowIndex, int mColIndex) {
				return false;
			}
		};
		setBounds(100, 100, 772, 434);
		getContentPane().setLayout(new BorderLayout(0, 0));
		getContentPane().add(getPanel(), BorderLayout.NORTH);
		getContentPane().add(getPanel_1(), BorderLayout.EAST);
		getContentPane().add(getScrollPane(), BorderLayout.CENTER);

	}

	private JPanel getPanel() {
		if (panel == null) {
			panel = new JPanel();
			panel.setLayout(new BorderLayout(0, 0));
			panel.add(getPanel_2(), BorderLayout.CENTER);
			panel.add(getPanel_3(), BorderLayout.EAST);
		}
		return panel;
	}

	private JPanel getPanel_1() {
		if (panel_1 == null) {
			panel_1 = new JPanel();
			panel_1.setPreferredSize(new Dimension(250, 10));
			panel_1.add(getLblNewLabel());
			panel_1.add(getCode());
			panel_1.add(getLabel());
			panel_1.add(getIrum());
			panel_1.add(getLabel_1());
			panel_1.add(getPric());
			panel_1.add(getLabel_2());
			panel_1.add(getCustomer());
			panel_1.add(getLabel_3());
			panel_1.add(getEA());
			panel_1.add(getLabel_4());
			panel_1.add(getSaleEa());
			panel_1.add(getPanel_4());
			panel_1.add(getBtnNewButton_1());
		}
		return panel_1;
	}

	private JTextField getCode() {
		if (code == null) {
			code = new JTextField();
			code.setEditable(false);
			code.setColumns(15);
		}
		return code;
	}

	private JLabel getLblNewLabel() {
		if (lblNewLabel == null) {
			lblNewLabel = new JLabel("제품 코드");
			lblNewLabel.setPreferredSize(new Dimension(52, 25));
		}
		return lblNewLabel;
	}

	private JLabel getLabel() {
		if (label == null) {
			label = new JLabel("제품명");
			label.setHorizontalAlignment(SwingConstants.CENTER);
			label.setPreferredSize(new Dimension(52, 25));
		}
		return label;
	}

	private JTextField getIrum() {
		if (irum == null) {
			irum = new JTextField();
			irum.setEditable(false);
			irum.setColumns(15);
		}
		return irum;
	}

	private JLabel getLabel_1() {
		if (label_1 == null) {
			label_1 = new JLabel("판매가");
			label_1.setPreferredSize(new Dimension(52, 25));
			label_1.setHorizontalAlignment(SwingConstants.CENTER);
		}
		return label_1;
	}

	private JTextField getPric() {
		if (pric == null) {
			pric = new JTextField();
			pric.setEditable(false);
			pric.setColumns(15);
		}
		return pric;
	}

	private JLabel getLabel_2() {
		if (label_2 == null) {
			label_2 = new JLabel("거래처");
			label_2.setPreferredSize(new Dimension(52, 25));
			label_2.setHorizontalAlignment(SwingConstants.CENTER);
		}
		return label_2;
	}

	private JTextField getCustomer() {
		if (customer == null) {
			customer = new JTextField();
			customer.setEditable(false);
			customer.setColumns(15);
		}
		return customer;
	}

	private JLabel getLabel_3() {
		if (label_3 == null) {
			label_3 = new JLabel("재고");
			label_3.setPreferredSize(new Dimension(52, 25));
			label_3.setHorizontalAlignment(SwingConstants.CENTER);
		}
		return label_3;
	}

	private JTextField getEA() {
		if (EA == null) {
			EA = new JTextField();
			EA.setEditable(false);
			EA.setColumns(15);
		}
		return EA;
	}

	private JLabel getLabel_4() {
		if (label_4 == null) {
			label_4 = new JLabel("판매수량");
			label_4.setPreferredSize(new Dimension(52, 25));
			label_4.setHorizontalAlignment(SwingConstants.CENTER);
		}
		return label_4;
	}

	private JTextField getSaleEa() {
		if (saleEa == null) {
			saleEa = new JTextField();
			saleEa.addKeyListener(new KeyAdapter() {
				@Override
				public void keyReleased(KeyEvent arg0) {
					try {
						if (saleEa.getText().equals("")) {
							return;
						}
						int ea = Integer.parseInt(EA.getText());
						int sale = Integer.parseInt(saleEa.getText());
						if (sale > ea) {
							JOptionPane.showMessageDialog(null,
									"해당 제품의 제고가 부족합니다.");
							saleEa.setText("");
						} else if (sale <= 0) {
							JOptionPane.showMessageDialog(null,
									"판매 수량을 정확히 입력해주세요.");
							saleEa.setText("");
						}
					} catch (Exception ev) {
						JOptionPane.showMessageDialog(null,
								"판매 수량을 정확히 ^^ 입력해주세요.");
						saleEa.setText("");
						saleEa.requestFocus();
						return;

					}
				}
			});
			saleEa.setColumns(15);
		}
		return saleEa;
	}

	private JPanel getPanel_2() {
		if (panel_2 == null) {
			panel_2 = new JPanel();
			panel_2.setLayout(new BorderLayout(0, 0));
			panel_2.add(getTextField_6_1());
			panel_2.add(getBtnNewButton(), BorderLayout.EAST);
		}
		return panel_2;
	}

	private JPanel getPanel_3() {
		if (panel_3 == null) {
			panel_3 = new JPanel();
			panel_3.setPreferredSize(new Dimension(250, 10));
		}
		return panel_3;
	}

	private JTextField getTextField_6_1() {
		if (findStr == null) {
			findStr = new JTextField();
			findStr.addKeyListener(new KeyAdapter() {
				@Override
				public void keyReleased(KeyEvent e) {
					if (e.getKeyCode() == KeyEvent.VK_ENTER) {
						search();
					}
				}
			});
			findStr.setColumns(10);
		}
		return findStr;
	}

	private JButton getBtnNewButton() {
		if (btnNewButton == null) {
			btnNewButton = new JButton("조회");
			btnNewButton.setPreferredSize(new Dimension(80, 23));
			btnNewButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					search();
				}
			});
		}
		return btnNewButton;
	}

	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setViewportView(getTable());
		}
		return scrollPane;
	}

	private boolean search() {
		try {

			model.setRowCount(0);
			String str = findStr.getText();

			Statement stmt = con.createStatement();

			// 가져올 자료 요청
			String sql = "select c.pro_code,c.pro_nm,ltrim(to_char(c.pro_price*1.2,'999,999,999')), cu.name, nvl(s.s_amount,0)"
					+ " from code c inner join customer cu "
					+ "on c.pro_cs_no=cu.num full outer join stock s "
					+ "on s.s_code=c.pro_code where c.pro_code like '%"
					+ str
					+ "%' or c.pro_nm like '%"
					+ str
					+ "%' or cu.name like '%"
					+ str + "%'";

			ResultSet RS = stmt.executeQuery(sql);

			while (RS.next()) {
				Vector<String> row = new Vector<String>();
				row.add(RS.getString(1));
				row.add(RS.getString(2));
				row.add(RS.getString(3) + "원");
				row.add(RS.getString(4));
				row.add(RS.getString(5));
				model.addRow(row);

			}
			RS.close();
			stmt.close();

			DefaultTableCellRenderer Center = new DefaultTableCellRenderer();
			Center.setHorizontalAlignment(SwingConstants.CENTER); // 가운데 정렬
			DefaultTableCellRenderer Right = new DefaultTableCellRenderer();
			Right.setHorizontalAlignment(SwingConstants.RIGHT);// 우측 정렬
			TableColumnModel tcmSchedule = table.getColumnModel();
			tcmSchedule.getColumn(0).setCellRenderer(Center);
			tcmSchedule.getColumn(1).setCellRenderer(Center);
			tcmSchedule.getColumn(2).setCellRenderer(Right);
			tcmSchedule.getColumn(3).setCellRenderer(Center);
			tcmSchedule.getColumn(4).setCellRenderer(Right);

			table.getTableHeader().setReorderingAllowed(false);
			table.getTableHeader().setResizingAllowed(false);
			table.setRowSorter(new TableRowSorter(model));
			
			return true;
		} catch (Exception e) {
			System.out.println("예외사항:" + e.getMessage());
			return false;
		}
	}

	public String replace(String s) {
		String temp = s.replace(",", "");
		String temp2 = temp.replace("원", "");
		return temp2;
	}

	private boolean sale() {
		try {
			SalStock ss = new SalStock();
			Statement stmt = con.createStatement();
			String cod = code.getText();
			String cname = irum.getText();
			int price = Integer.parseInt(replace(pric.getText()));
			int ea = Integer.parseInt(saleEa.getText());
			int tot = Integer.parseInt(EA.getText());
			ss.buy(cod, ea);

			// 가져올 자료 요청
			String sql = "insert into sale values(sa_no.nextval, '" + cod
					+ "'," + ea + ", " + price * ea
					+ ", '0', sysdate, '"+m.member+"', sysdate, '"+m.member+"')";
			ResultSet RS2 = stmt.executeQuery(sql);

			String sql2 = "insert into sale_history(sa_no,sa_info,in_de,sa_mem) values(sa_no.currval,'판매', "
					+ ea + ", '"+m.member+"')"; // 판매기록 입력
			ResultSet RS = stmt.executeQuery(sql2);
			model.setValueAt(tot - ea, index, 4);
			JOptionPane.showMessageDialog(null, "제품판매완료");
			RS2.close();
			RS.close();
			stmt.close();

			code.setText("");
			irum.setText("");
			pric.setText("");
			customer.setText("");
			saleEa.setText("");
			EA.setText("");

			return true;
		} catch (Exception e) {
			System.out.println("예외사항:" + e.getMessage());
			return false;
		}
	}

	public void mouseC() {
		index = table.getSelectedRow(); // 선택된 열의 table index번호를 저장

		code.setText(table.getValueAt(index, 0) + ""); //
		irum.setText(table.getValueAt(index, 1) + ""); //
		pric.setText(table.getValueAt(index, 2) + ""); //
		customer.setText(table.getValueAt(index, 3) + ""); //
		EA.setText(table.getValueAt(index, 4) + ""); //

	}

	private JTable getTable() {
		if (table == null) {
			table = new JTable(model);
			table.addMouseListener(new MouseAdapter() {
				@Override
				public void mouseReleased(MouseEvent arg0) {
					mouseC();
				}
			});
		}
		return table;
	}

	private JButton getBtnNewButton_1() {
		if (btnNewButton_1 == null) {
			btnNewButton_1 = new JButton("판매");
			btnNewButton_1.setPreferredSize(new Dimension(80, 23));
			btnNewButton_1.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					sale();
				}
			});
		}
		return btnNewButton_1;
	}

	private JPanel getPanel_4() {
		if (panel_4 == null) {
			panel_4 = new JPanel();
			panel_4.setPreferredSize(new Dimension(150, 10));
		}
		return panel_4;
	}
}
